<?php
namespace backend\models;

use Yii;
use yii\base\Model;
use yii\base\Exception;
use common\models\User;

class UserForm extends Model
{
	public $username;
	public $password;
	public $confirm_password;
	public $eid;
	public $id;
	public $status;

	private $_user;

	public function __construct($id=null, $config = [])
	{
		if (!empty($id)) {
			$user = User::findOne($id);
			$this->username = $user->username;
			$this->eid = $user->eid;
			$this->id = $user->id;
		} else {
			$user = new User;
		}
		$this->_user = $user;

		return parent::__construct($config);
	}

	public function formName()
    {
        return '';
    }

	public function rules()
	{
		return [
			[['username', 'password', 'confirm_password', 'eid'], 'required'],
			['username', 'validateUsername'],
			['confirm_password', 'validatePassword'],
			['eid', 'validateEmployee']
		];
	}

	public function validateUsername($attribute, $params)
	{
		if (!$this->hasErrors()) {
			$user_obj = User::find()->where(['username' => $this->username])->one();
			if ($user_obj) {
				$this->addError($attribute, '用户名已存在');
			}
		}
	}

	public function validatePassword($attribute, $params)
	{
		if (!$this->hasErrors()) {
			if ($this->password != $this->confirm_password) {
				$this->addError($attribute, '两次密码不一致');
			}
		}
	}

	public function validateEmployee($attribute, $params)
	{
		if (!$this->hasErrors()) {
			$user_obj = User::find()->where(['eid' => $this->eid, 'status' => User::STATUS_ACTIVE])->one();
			if ($user_obj) {
				$this->addError($attribute, '该员工已经分配过管理员账户');
			}
		}
	}

	public function addOrUpdate()
	{
        $user = $this->_user;
        $user->username = $this->username;
        $user->setPassword($this->password);
        $user->generateAuthKey();
        $user->eid = $this->eid;
        $user->status = User::STATUS_ACTIVE;
        
        return $user->save() ? true : false;
	}

}	